import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
// import Cookies from 'js-cookie';
import { getToken, getUserInfo } from '@/utils/auth'
import _tools from '@/utils/_tools';
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 1800000, // request timeout
  onUploadProgress: (progressEvent) => {
    // 显示上传进度，增强用户体验
    const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
    console.log(`上传进度: ${percent}%`);
  }
})

// request interceptor
service.interceptors.request.use(
  config => {
    // config.data ? config.data = config.data : config.data = {};
    // if (config.data instanceof FormData) {
    // } else {
    // }

    if (config.method == 'get') {
      config.data ? config.params = config.data : config.params = {};
    } else {
      config.data ? config.data = config.data : config.data = {};
      if (config.data instanceof FormData) {
      } else {
      }
    }

    // console.log(config.data, config.url,config.data instanceof FormData);
    config.headers['Content-Type'] = 'application/json';

    var token = getToken();

    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    } else {
      config.headers['Authorization'] = `Basic ${localStorage.getItem('user_login')}`;
    }

    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    try {
      let res = response.data
      res = JSON.parse(_tools.decode_h(res))
      return res
    } catch (error) {
      Message({
        message: '解密错误',
        type: 'error',
        duration: 5 * 1000
      })
    }
  },
  error => {
    if (error.response.status == 401) {
      MessageBox.alert('您的身份验证已经失效，请重新登陆!', "提示", {
        confirmButtonText: '确定',
        showClose: false,
        type: 'warning',
        showCancelButton: false,
      }).then(() => {
        store.dispatch('user/logout').then(() => {
          window.location.href = "/login";
        });
      });
    } else if (error.response.status == 422) {
      Message({
        message: error.response.data.message,
        type: 'error',
        duration: 5 * 1000
      })
      return error
    } else if (error.response.status == 500) {
      // if (url == 'shareRecord/shareContent') {
      //   return;
      // }
      Message({
        message: '系统错误，赶快去联系后端程序猿！',
        type: 'error',
        duration: 5 * 1000
      })
      // return error
    } else if (error.response.status == 405) {
      Message({
        message: '请求方式错误',
        type: 'error',
        duration: 5 * 1000
      })
      // return error
    }

  }
)

export default service
